{
 "cells": [
  {
   "cell_type": "raw",
   "id": "8980c8b0",
   "metadata": {},
   "source": [
    "---\n",
    "sidebar_position: 7\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c3f1df8",
   "metadata": {},
   "source": [
    "# Self ask with search\n",
    "\n",
    "Поиск ответа в интернете с промежуточными вопросами"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2018da2d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, create_self_ask_with_search_agent\n",
    "from langchain_community.llms import Fireworks\n",
    "from langchain_community.tools.tavily_search import TavilyAnswer"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "527080a7",
   "metadata": {},
   "source": [
    "## Initialize Tools\n",
    "\n",
    "We will initialize the tools we want to use. This is a good tool because it gives us **answers** (not documents)\n",
    "\n",
    "For this agent, only one tool can be used and it needs to be named \"Intermediate Answer\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "655bcacd",
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = [TavilyAnswer(max_results=1, name=\"Intermediate Answer\")]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cec881b8",
   "metadata": {},
   "source": [
    "## Create Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9860f2e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get the prompt to use - you can modify this!\n",
    "prompt = hub.pull(\"hwchase17/self-ask-with-search\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0ac6b463",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Choose the LLM that will drive the agent\n",
    "llm = Fireworks()\n",
    "\n",
    "# Construct the Self Ask With Search Agent\n",
    "agent = create_self_ask_with_search_agent(llm, tools, prompt)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a2e90540",
   "metadata": {},
   "source": [
    "## Run Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6677fa7f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create an agent executor by passing in the agent and tools\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "fff795f0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mДа.\n",
      "Дополнительный вопрос: Кто придумал психотипы?\u001b[0m\n",
      "Промежуточный ответ: \u001b[36;1m\u001b[1;3mПсихотип. Психологический тип –это теория личности, созданная швейцарским психиатром Карлом Густавом Юнгом для объяснения нормальных различий здоровых людей ...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mДополнительный вопрос: Как звали жену Карла Густава Юнга?\u001b[0m\n",
      "Промежуточный ответ: \u001b[36;1m\u001b[1;3mEmma Jung\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mИтак, окончательный ответ: Emma Jung\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': \"What is the hometown of the reigning men's U.S. Open champion?\",\n",
       " 'output': 'Novak Djokovic.'}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.agents import AgentType, Tool, initialize_agent\n",
    "from langchain.chat_models import ChatOpenAI, GigaChat\n",
    "from langchain.llms import OpenAI\n",
    "from langchain.utilities import SerpAPIWrapper\n",
    "\n",
    "# llm = GigaChat(credentials=..., verbose=True)\n",
    "llm = ChatOpenAI(model=\"gpt-4\", openai_api_key=\"<sk-...>\")\n",
    "search = SerpAPIWrapper()\n",
    "tools = [\n",
    "    Tool(\n",
    "        name=\"Промежуточный ответ\",\n",
    "        func=search.run,\n",
    "        description=\"Используется, когда нужно вопспользоваться поиском\",\n",
    "    )\n",
    "]\n",
    "\n",
    "self_ask_with_search = initialize_agent(\n",
    "    tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True\n",
    ")\n",
    "self_ask_with_search.run(\"Как звали жену человека, который придумал психотипы\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74482369-7b8b-4080-bd2e-f0e7a13be432",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## Используем внутренний агент"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "b2e4d6bc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mДа.\n",
      "Дополнительный вопрос: Какова стоимость 1 биткоина?\u001b[0m\n",
      "Промежуточный ответ: \u001b[36;1m\u001b[1;3mЛоготип. Bitcoin. 25823.7$. Стоимость. 221 302 000$. Объём 24ч. Логотип. Ethereum. 1629.13$. Стоимость. 104 832 000$. Объём 24ч. Логотип.\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mДополнительный вопрос: Сколько стоит самый дешевый автомобиль?\u001b[0m\n",
      "Промежуточный ответ: \u001b[36;1m\u001b[1;3mBajaj Qute – самый дешевый автомобиль в мире. У себя на родине, в Индии, он стоит 3 400 долларов. В пересчете на рубли это 193 тысяч. Компания, ...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mИтак, окончательный ответ: Примерно 7 автомобилей.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Примерно 7 автомобилей.'"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "self_ask_with_search = initialize_agent(\n",
    "    tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True\n",
    ")\n",
    "self_ask_with_search.run(\"Сколько можно купить самых дешевых автомобилей за 1 биткоин?\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  },
  "vscode": {
   "interpreter": {
    "hash": "b1677b440931f40d89ef8be7bf03acb108ce003de0ac9b18e8d43753ea2e7103"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
